<template>
  <div class="login" @keyup.enter="handleSubmit('formInline')">
    <!-- 顶部logo -->
    <div style="height:50px;"></div>
    <div class="top-content" @click='$refs.verify.show = false'>
      <div class="logo-box">
        <img
            :src="logoImg"
            style="margin-right: 15%"
            width="150"
            @click="$router.push('/')"
        />
        <div>{{ $t('welcomeLogin.welcome') }}</div>
      </div>
    </div>

    <!-- 登錄主体 包含轮播图 登錄模塊 -->
    <div class="login-container">
      <!-- 登錄模塊 -->
      <div class="form-box" @click='$refs.verify.show = false'>
        <div class="account-number">
          <div class="tab-switch">
            <span>{{ type ? $t('welcomeLogin.acount') : $t('welcomeLogin.code') }}</span>
            <span @click="type = !type,scannerCodeLoginFLag=false">{{ type ? $t('welcomeLogin.code') : $t('welcomeLogin.acount') }}</span>
          </div>
          <!---->
          <!--          <div @click="scannerCodeLoginFLag=!scannerCodeLoginFLag">{{ !scannerCodeLoginFLag ? '掃碼登錄' : '返回' }}
                    </div>-->
        </div>
        <!--掃碼登錄-->
        <div v-show="scannerCodeLoginFLag">
          <div class="qr-container">
            <div v-show="qrCodeStatus == 'fail'" class='qr-shadow flex'>
              <span>
                二維碼已失效
              </span>
              <Button size='small' @click="createPCLoginSession">刷新二維碼</Button>
            </div>
            <vue-qr
                :margin="0"
                :size="150"
                :text="qrCode"
                colorDark="#000"
                colorLight="#fff"
            ></vue-qr>
          </div>
          <div class="drag-area">
            <!--    等待掃碼-->
            <div v-if="scannerCodeLoginStatus === 0" class="pending-scan">
              <p>打开手機App/小程序，掃碼登錄</p>
            </div>
            <!--    已经掃碼-->
            <div v-else-if="scannerCodeLoginStatus === 1" class="scanned">
              <p>掃碼成功，等待確認</p>
            </div>

            <!--    存在session，等待發送给客戶端驗證-->
            <div v-if="scannerCodeLoginStatus === 2" class="scanned">
              <p>登錄成功，正在頁面跳轉</p>
            </div>

            <!--    已经發送登錄請求-->
            <div v-else-if="scannerCodeLoginStatus === 3" class="quick-logining">
              <p>取消登錄</p>
            </div>
          </div>
        </div>

        <div>
          <div v-show="!scannerCodeLoginFLag">
            <!-- 賬號密碼登錄 -->
            <Form v-show="type === true" ref="formInline" :model="formData" :rules="ruleInline"
                  style="width:300px;" @click.self='$refs.verify.show = false'>
              <FormItem prop="username">
                <i-input v-model="formData.username" clearable :placeholder="$t('welcomeLogin.username')" type="text">
                  <Icon slot="prepend" type="md-person"></Icon>
                </i-input>
              </FormItem>
              <FormItem prop="password">
                <i-input v-model="formData.password" clearable :placeholder="$t('welcomeLogin.password')" type="password">
                  <Icon slot="prepend" type="md-lock"></Icon>
                </i-input>
              </FormItem>
              <FormItem>
                <Button long type="error" @click.stop="handleSubmit('formInline')">{{ $t('welcomeLogin.login') }}</Button>
              </FormItem>
            </Form>
            <!-- 驗證碼登錄 -->
            <Form v-show="type === false" ref="formSms" :model="formSms" :rules="ruleInline"
                  @click.self='$refs.verify.show = false'>
              <FormItem prop="mobile">
                <i-input v-model="formSms.mobile" clearable placeholder="手機號" type="text">
                  <Icon slot="prepend" type="md-lock"></Icon>
                </i-input>
              </FormItem>
              <FormItem prop="code">
                <i-input v-model="formSms.code" placeholder="手機驗證碼" type="text">
                  <Icon slot="prepend" style="font-weight: bold" type="ios-text-outline"/>
                  <Button slot="append" @click="sendCode">{{ codeMsg }}</Button>
                </i-input>
              </FormItem>
              <FormItem>
                <Button :type="verifyStatus?'success':'default'" long
                        @click.stop="verifyBtnClick">{{ verifyStatus ? '驗證通过' : '點擊完成安全驗證' }}
                </Button>
              </FormItem>
              <FormItem>
                <Button long type="error" @click="handleSubmit('formSms')">{{ $t('welcomeLogin.login') }}</Button>
              </FormItem>
            </Form>
          </div>
          <div class="other">
            <div class="register">
              <span style="color:red" @click="$router.push('signUp')">{{ $t('welcomeLogin.noacount') }}</span>
              <span @click="$router.push({ name: 'forgetPassword', query: {storeId:storeId} })">{{ $t('welcomeLogin.forget') }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 拼图驗證碼 -->
      <verify ref="verify" class="verify-con" verifyType="LOGIN" @change="verifyChange"></verify>
    </div>
    <div class="foot">
<!--      <Row class="help" justify="space-around" type="flex">-->
<!--        <router-link class="item" target="_blank" to="/article">帮助</router-link>-->
<!--        <router-link class="item" target="_blank" to="/article?id=1371779927900160000">隐私</router-link>-->
<!--        <router-link class="item" target="_blank" to="/article?id=1371992704333905920">條款</router-link>-->
<!--      </Row>-->
      <Row class="copyright" justify="center" type="flex">
        Copyright ©
        <a href="https://pickmall.cn" style="margin: 0 5px" target="_blank">{{ config.title }}</a>
        版权所有
      </Row>
    </div>
  </div>
</template>

<script>

import {md5} from "@/plugins/md5.js";
import * as apiLogin from "@/api/login.js";
import {getSCLoginCode, loginCallback, sCLogin, webLogin} from "@/api/login.js";
import {sendSms} from "@/api/common.js";
import storage from "@/plugins/storage.js";
import verify from "@/components/verify";
import vueQr from "vue-qr";
import i18n from "@/lang";
export default {
  i18n,
  name: "Login",
  components: {
    verify,
    vueQr
  },
  data() {
    return {
      qrCodeStatus: "success", //
      qrCode: '',
      qrSessionToken: '',
      logoImg: '',
      //是否是二維碼登錄
      scannerCodeLoginFLag: false,
      scannerCodeLoginStatus: 0,
      qrCodeTimer: null,
      config: require('@/config'),
      storeId: window.localStorage.getItem('storeId'),
      type: true, // true 賬號登錄  false 驗證碼登錄
      formData: {
        // 登錄表單
        username: "",
        password: "",
      },
      formSms: {
        // 手機號登錄
        code: "",
        mobile: "",
      },
      verifyStatus: false, // 是否图片驗證通过
      ruleInline: {
        // 驗證规则
        username: [{required: true, message: "請輸入用戶名"}],
        password: [
          {required: true, message: "請輸入密碼"},
          {type: "string", min: 6, message: "密碼不能少於6位"},
        ],
        mobile: [
          {required: true, message: "請輸入手機號碼"},
          {
            pattern: RegExp.mobile,
            message: "請輸入正确的手機號",
          },
        ],
        code: [{required: true, message: "請輸入手機驗證碼"}],
      },
      codeMsg: "發送驗證碼", // 驗證碼文字
      interval: null, // 定時器
      time: 60, // 倒计時
      year: new Date().getFullYear(),
    };
  },
  methods: {
    // 登錄
    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (this.type) {
            this.$refs.verify.init();
          } else {
            let data = JSON.parse(JSON.stringify(this.formSms));
            apiLogin.smsLogin(data).then((res) => {
              this.$refs.verify.show = false;
              if (res.success) {
                this.$Message.success("登錄成功");
                storage.setItem("accessToken", res.result.accessToken);
                storage.setItem("refreshToken", res.result.refreshToken);
                storage.setItem('getTimes', 0)
                apiLogin.getMemberMsg().then((res) => {
                  if (res.success) {
                    storage.setItem("userInfo", res.result);
                    let query = this.$route.query;
                    if (query.rePath) {
                      this.$router.push({
                        path: query.rePath,
                        query: JSON.parse(query.query),
                      });
                    } else {
                      this.$router.push("/");
                    }
                  }
                });
              } else {
                this.$Message.error(res.message);
              }
            });
          }
        }
      });
    },
    // 發送手機驗證碼
    sendCode() {
      if (this.time === 60) {
        if (this.formSms.mobile === "") {
          this.$Message.warning("請先填写手機號");
          return;
        }
        if (!this.verifyStatus) {
          this.$Message.warning("請先完成安全驗證");
          return;
        }
        let params = {
          mobile: this.formSms.mobile,
          verificationEnums: "LOGIN",
        };
        sendSms(params).then((res) => {
          if (res.success) {
            this.$Message.success("驗證碼發送成功");
            let that = this;
            this.interval = setInterval(() => {
              that.time--;
              if (that.time === 0) {
                that.time = 60;
                that.codeMsg = "重新發送";
                that.verifyStatus = false;
                clearInterval(that.interval);
              } else {
                that.codeMsg = that.time;
              }
            }, 1000);
          } else {
            this.$Message.warning(res.message);
          }
        });
      }
    },
    verifyChange(con) {
      // 拼图驗證碼回显
      if (!con.status) return;

      if (this.type === true) {
        // 賬號密碼登錄
        let data = JSON.parse(JSON.stringify(this.formData));
        data.password = md5(data.password);
        this.$refs.verify.show = false;
        this.$Spin.show();
        apiLogin
            .login(data)
            .then((res) => {
              if (res.success) {
                this.loginSuccess(res.result.accessToken, res.result.refreshToken);
              } else {
                this.$Spin.hide();
                this.$Message.error(res.message);
              }
            })
            .catch(() => {
              this.$Spin.hide();
            });
      } else {
        this.verifyStatus = true;
        this.$refs.verify.show = false;
      }
    },
    // 开启滑塊驗證
    verifyBtnClick() {
      if (!this.verifyStatus) {
        this.$refs.verify.init();
      }
    },
    handleWebLogin(type) {
      // 第三方登錄
      webLogin(type);
    },
    loginSuccess(accessToken, refreshToken) {
      this.$Message.success("登錄成功");
      storage.setItem("accessToken", accessToken);
      storage.setItem("refreshToken", refreshToken);
      apiLogin.getMemberMsg().then((res) => {
        this.$Spin.hide();
        if (res.success) {
          res.result.face = 'https://ui-avatars.com/api/?background=1890ff&color=fff&name=' + res.result.nickName;
          storage.setItem("userInfo", res.result);
          let query = this.$route.query;
          if (query.rePath) {
            this.$router.push({
              path: query.rePath,
              query: JSON.parse(query.query),
            });
          } else {
            this.$router.push("/");
          }
        }
      });
    },

    async createPCLoginSession() {
      getSCLoginCode({}).then(response => {
        this.clearQRLoginInfo();
        if (response.code == 200) {
          this.qrCodeStatus = 'success'
          let session = response.result;
          this.qrSessionToken = session.token;
          if (session.status === 0) {
            this.qrCode = session.token;
            this.refreshQrCode();
          }
          this.qrLogin();

        }
      });
    },

    async refreshQrCode() {
      if (!this.qrCodeTimer) {
        this.qrCodeTimer = setInterval(() => {

          this.qrCodeStatus = 'fail' // 如果过期将二維碼轉为失效狀態
        }, 10 * 1000);
      }
    },

    clearQRLoginInfo() {
      this.scannerCodeLoginStatus = 0;
      this.qrSessionToken = '';
      if (this.qrCodeTimer) {
        clearInterval(this.qrCodeTimer)
      }
      this.qrCodeTimer = null;
    },

    async qrLogin() {
      if (!this.qrSessionToken) return;
      sCLogin(this.qrSessionToken, {beforeSessionStatus: this.scannerCodeLoginStatus}).then(response => {
        if (response.success) {
          this.scannerCodeLoginStatus = response.result.status;
          switch (response.result.status) {
            case 0:
            case 1:
              this.qrLogin();
              break;
            case 2:
              this.loginSuccess(response.result.token.accessToken, response.result.token.refreshToken);
              break;
            case 3:
              this.createPCLoginSession();
              break;
            default:
              this.clearQRLoginInfo();
              break
          }
        } else {
          this.clearQRLoginInfo();
        }
      });
    },
  },
  destroyed() {
    this.clearQRLoginInfo();
  },
  mounted() {
    let uuid = this.$route.query.state;
    if (uuid) {
      storage.setItem("uuid", uuid);
      loginCallback(uuid).then((res) => {
        if (res.success) {
          this.loginSuccess(res.result.accessToken, res.result.refreshToken);
        }
      });
    }
    document.querySelector('.login').style.height = window.innerHeight + 'px'
  },
  created() {
    // 店铺ID
    this.logoImg = require('@/assets/images/logo' + window.localStorage.getItem("storeId") + '.png');
    this.config= require('@/config/right'+window.localStorage.getItem('storeId')+'.js');
  },
  watch: {
    scannerCodeLoginFLag(v) {
      if (v) {
        this.createPCLoginSession();
        console.log("二維碼登錄");
      } else {
        console.log("取消二維碼登錄");
        this.clearQRLoginInfo();
      }
    },
    type(v) {
      if (v) {
        this.$refs.formInline.resetFields();
      } else {
        this.$refs.formSms.resetFields();
      }
      this.verifyStatus = false;
      this.$refs.verify.show = false;
      clearInterval(this.interval);
      this.codeMsg = "發送驗證碼";
      this.time = 60;
    }
  },
};
</script>
<style lang="scss" scoped>
.drag-area {
  margin: 10px 0;
}

.qr-container {
  text-align: center;
  margin: 20px 0;
  position: relative;

  > .qr-shadow {
    background: rgba(0, 0, 0, 0.45);
    position: absolute;
    left: 50%;
    margin-left: -75px;
    top: 0;
    z-index: 99;
    width: 150px;
    height: 150px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    color: #fff;

    > span {
      margin-bottom: 20px;
      font-size: 13px;
      letter-spacing: 2px;
    }
  }
}

.top-content {
  width: 100%;
  height: 80px;
  position: relative;

  .logo-box {
    width: 600px;
    height: 80px;
    margin: 0 auto;
    display: flex;
    align-items: center;

    img {
      width: 150px;
      cursor: pointer;
    }

    div {
      font-size: 20px;
      margin-top: 10px;
    }
  }
}

.pending-scan {
  text-align: center;
  color: black;
}

.scanned {
  text-align: center;
  color: green;
}

.quick-logining {
  text-align: center;
  color: red;
}

.login-carousel {
  width: 100%;
  height: 550px;

  .demo-carousel {
    height: 550px;
    width: inherit;
    display: flex;
    justify-content: center;
  }
}

.login-container {
  border-top: 2px solid $theme_color;
  position: relative;
  margin: 0 auto;
  width: 600px;
  background-color: #fff;
  padding: 20px 150px;

  .login-btn {
    position: absolute;
    right: 20px;
    top: -45px;
  }
}

.form-box {
  width: 350px;
  box-sizing: border-box;
  /*position: absolute;*/
  top: 80px;
  right: 15%;
  padding: 20px;
  background: rgba(255, 255, 255, 0.8);

  .account-number {
    display: flex;
    justify-content: space-between;
    align-items: baseline;
    font-weight: bold;

    > div:nth-child(2) {
      color: $theme_color;
      cursor: pointer;
    }

    .tab-switch {
      height: 40px;
      font-size: 14px;

      span:nth-child(1) {
        font-size: 16px;
        border-right: 1px solid #ddd;
        padding-right: 10px;
      }

      span:nth-child(2) {
        cursor: pointer;
        padding-left: 10px;

        &:hover {
          color: $theme_color;
        }
      }
    }
  }
}

.verify-con {
  position: absolute;
  right: 16%;
  top: 90px;
  z-index: 10;
}

.other-login {

  > svg {
    cursor: pointer;
    width: 24px;
    margin-right: 10px;
    height: 24px;
  }
}

.register {
  display: flex;

  margin-top: -10px;

  span {
    margin-left: 10px;

    &:hover {
      cursor: pointer;
      color: $theme_color;
    }
  }
}

.foot {
  position: fixed;
  bottom: 4vh;
  width: 368px;
  left: calc(50% - 184px);
  color: rgba(0, 0, 0, 0.45);
  font-size: 14px;

  .help {
    margin: 0 auto;
    margin-bottom: 1vh;
    width: 60%;

    .item {
      color: rgba(0, 0, 0, 0.45);
    }

    :hover {
      color: rgba(0, 0, 0, 0.65);
    }
  }
}

.icon-hover {
  cursor: pointer;
}

</style>
